package com.markyao.service.impl;

import com.markyao.dao.mapper.AddressMapper;
import com.markyao.dao.pojo.Address;
import com.markyao.service.AddressService;
import com.markyao.service.DictDistrictService;
import com.markyao.vo.LIMIT_NUM;
import com.markyao.vo.Result;
import com.markyao.vo.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    DictDistrictService dictDistrictService;
    @Override
    public Result addAddress(Address address) {
        //添加收获地址,需要两个sql语句：查找该用户的收货地址是否达到了上限(20个);插入数据库表
        int count=addressMapper.findCountByUid(address.getUid());
        if (count> LIMIT_NUM.MAX_ADDRESS_COUNT.getLimit()){
            return new Result(false,LIMIT_NUM.MAX_ADDRESS_COUNT.getMsg(), LIMIT_NUM.MAX_ADDRESS_COUNT.getLimit(),null);
        }
        String getProvinceCode = dictDistrictService.findByCode(address.getProvinceCode());
        String getCityCode = dictDistrictService.findByCode(address.getCityCode());
        String getAreaCode = dictDistrictService.findByCode(address.getAreaCode());
        address.setCreatedTime(new Date());
        address.setCreatedUser(address.getName());
        address.setAreaName(getAreaCode);
        address.setCityName(getCityCode);
        address.setProvinceName(getProvinceCode);
        addressMapper.addAddress(address);
        return new Result(true,ResultCode.ADD_SUCCESS.getMsg(), ResultCode.ADD_SUCCESS.getCode(), null);
    }

    @Override
    public Result findByUid(Integer uid) {
        List<Address> addressList=addressMapper.findByUid(uid);
        return new Result(true,"查找成功",1000,addressList);
    }

    @Override
    public Result setDefault(Integer aid, Integer uid) {
        //sql语句三条
        //确认该aid是否存在?
        //将用户的所有地址设为非默认
        //添加默认
        Address address=findByAid(uid,aid);
        if(address==null){
            return new Result(false,"您不存在这条地址信息",-999,null);
        }
        addressMapper.setNoDefault(uid);
        addressMapper.setDefault(aid);
        return new Result(true,"设置默认成功",1000,null);
    }

    @Override
    public Result delete(Integer aid, Integer uid) {
        //sql语句三条
        //确认该aid是否存在?
        //将用户的所有地址设为非默认
        //添加默认
        Address address=findByAid(uid,aid);
        if(address==null){
            return new Result(false,"您不存在这条地址信息",-999,null);
        }
        addressMapper.deleteByAid(aid);
        return new Result(true,"设置默认成功",1000,null);
    }

    @Override
    public Address findByAid(Integer uid, Integer aid) {
        return addressMapper.findByAid(uid,aid);
    }


}
